/*
* 文件：LogFile.cs
* 作者：王阳
* 时间：2019-5-20
* 描述：日志文件
*/

using System;
using System.IO;
using System.Text;
using UnityEngine;

namespace UnityX
{
    /// <summary>
    /// 日志文件
    /// </summary>
    internal class LogFile
    {
        private static FileStream logfile = null;
        /// <summary>
        /// 初始化日志文件
        /// </summary>
        public static void Init()
        {
#if UNITY_EDITOR
            if (logfile != null)
            {
                logfile.Close();
                logfile = null;
            }
#endif
            string directory;
            switch (Application.platform)
            {
                case RuntimePlatform.Android:
                case RuntimePlatform.IPhonePlayer:
                    directory = Application.persistentDataPath + "/Log";
                    break;
                default:
                    directory = "Log";
                    break;
            }
            try
            {
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                DateTime dateTime = DateTime.Now;
                logfile = File.Open(directory + "/" + dateTime.ToString("yyyy年MM月dd日HH时mm分ss秒") + ".txt", FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
                logfile.Seek(0, SeekOrigin.End);
            }
            catch (Exception e)
            {
                Debug.LogError("创建日志文件出错：" + e);
            }
        }
        /// <summary>
        /// 写消息到日志文件
        /// </summary>
        /// <param name="content"></param>
        /// <param name="time"></param>
        /// <param name="stack"></param>
        /// <param name="type"></param>
        public static void Write(string content, DateTime time, string stack, LogType type)
        {
            byte[] buff = Encoding.UTF8.GetBytes("[" + time.ToString() + " " + type + "] " + content + "\n" + stack + "\n");
            try
            {
                logfile.Write(buff, 0, buff.Length);
                logfile.Flush();
            }
            catch (Exception ex)
            {
                Debug.LogError("写日志到文件出错：" + ex);
            }
        }
    }
}